<template>
    <div>
      <el-button type='success' size="large" @click="state.mode='chapter'" text>章节目录</el-button>
      <el-button type='warning' size="large" @click="state.mode='tag'" text>知识点标签</el-button>
    </div>
    <div class="tag-mode" v-show="state.mode=='tag'">
      <el-button type="warning" @click="state.isEditTag=!state.isEditTag" text>编辑标签</el-button>
      <div class="tag-item" v-for="item in state.tagList" :key="item.id">
        <el-button text :type="getButtonType()" @click="onClickTagGetQuestion(item.id)" size="small">{{ item.name }}</el-button>
        <el-button v-show="state.isEditTag==true"  size="small" :icon="Setting" text @click="onClickEditTag(item)"></el-button>
      </div>
      <el-button :type="getButtonType()" size="large" @click="getTagAll" text>刷新标签</el-button>
      <el-dialog
        v-model="state.editTagDialogVisible"
        title="编辑标签"
        width="500"       
      >
        <el-input v-model="state.inputTagName" style="width: 240px" placeholder="输入标签名" />       
        <template #footer>
          <div class="dialog-footer">
            <el-button type="warning" @click="state.editTagDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onClickQueding">确定</el-button>        
          </div>
        </template>
      </el-dialog>
    </div>
    <div  class="node-mode" v-show="state.mode=='chapter'">
      <el-button type="warning" @click="swithEditNode" v-show="state.isEditNode==false" text>编辑节点</el-button>
      <el-button type="primary" @click="swithEditNode" v-show="state.isEditNode==true" text>关闭编辑</el-button>
      <el-tree
        style="max-width: 500px"
        highlight-current
        :data="state.chapterSectionMenu"
        :props="defaultProps"
        node-key="id"
        @node-click="handleNodeClick"
        :indent= state.indent
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span>{{ node.label }}</span> 
            <span v-if="state.isEditNode==false" style="color:green">--{{ data.question_count }}题</span>

            <div class="three-button" v-if="state.isEditNode==true">
              <el-tooltip effect="dark" content="新增子节点" placement="top">
                <Plus style="width: 1em; height: 1em; margin-right: 1px " @click.stop="append(data)" />
              </el-tooltip>
              <el-tooltip class="box-item" effect="light" content="删除节点" placement="bottom">
                <Minus style="width: 1em; height: 1em; margin-right: 1px" @click.stop="remove(data)"/>
              </el-tooltip>
              <el-tooltip class="box-item" effect="dark" content="修改" placement="top">
                <Setting style="width: 1em; height: 1em; margin-right: 1px" @click.stop="modify(data)" />
              </el-tooltip>
              <el-tooltip class="box-item" effect="dark" content="上调" placement="top">
                <Top style="width: 1em; height: 1em; margin-right: 1px" @click.stop="upward(data)" v-if="data.id > 1" />
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-tree>
      <el-dialog
        v-model="state.dialogVisible"
        title="新建/编辑课程"
        width="500"       
      >
        <el-input v-model="inputCourseName" style="width: 240px" placeholder="输入节点名" />       
        <template #footer>
          <div class="dialog-footer">
            <el-button type="warning" @click="state.dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addNode" v-show="state.addNodeVisible">确定</el-button>
            <el-button type="primary" @click="editNode" v-show="state.editNodeVisible">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

</template>
  
<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import axios from '@/utils/axios'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Plus, Minus, Setting, Top } from '@element-plus/icons-vue'
// 通过结构，获得appContext变量
const { appContext } = getCurrentInstance()
// 获得全局上下文后， 得到$bus事件总线
const eventBus = appContext.config.globalProperties.$bus
  // 订阅本组件的事件,本组件收到命令后，模式切换到tag模式，并重新获取tag
  eventBus.on('tagModeWaitShowQuestion',()=>{
    state.mode = 'tag'
    getCategoryData()
  })
const buttonTypeList = ['primary', 'success', 'info', 'warning', 'danger']
  const getButtonType =()=>{
    let value = Math.floor(Math.random() * buttonTypeList.length)
    return buttonTypeList[value % buttonTypeList.length]
  }
const store=useStore()
const defaultProps = {
  children: 'children',
  label: 'name',
}
const inputCourseName = ref('')
const state = reactive({
  deleteTagMode: false,
  tagList: [],
  mode: 'chapter',
  chapterSectionMenu:[],
  subjectList:[],
  selectedSubjectId: '1',
  isEditNode: false,
  isEditTag: false,
  selectedNode: {id:0, name:''},
  dialogVisible: false,
  addNodeVisible: false,
  editNodeVisible: false,
  indent: 3,
  editTagDialogVisible: false,
  selectedTag: {id:0, name:''},
  inputTagName: '',
})
const router = useRouter()
const props = defineProps({
    id: Number,
});
// 编辑标签名字，的前期准备
const onClickEditTag = (tag) =>{
  console.log('点击了修改标签按钮：', tag)
  console.log('editTagDialogVisible的值：',state.editTagDialogVisible)
  state.selectedTag = tag
  state.inputTagName = tag.name
  state.editTagDialogVisible = true
}
// 确定提交修改标签
const onClickQueding = ()=>{
  console.log('要修改tag的名称啦')
  if(state.selectedTag.id==0 || state.inputTagName==''){
    ElMessage.warning( '请先选择标签，并输入名称')
    return 0
  }
  let params = {
      name: state.inputTagName,
      tag_id: state.selectedTag.id,
  }
  axios.put(`/TagModelViewSet/modify_name/`, params).then((res) => {
    if(res.code==200){
      ElMessage.success('修改成功')
      // state.nodeTree = res.data.results
      state.editTagDialogVisible = false;
      getTagAll()
    }else
    if(res.code==1099){
      ElMessage.warning( '标题不能为空！')
    }
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}
// 获取某个标签下的试题
const onClickTagGetQuestion = (id)=>{
  console.log('点击一个标签了:', id)
  state.selectedTag = {id: id, name:''}
  let params={'selectedTag': state.selectedTag, mode:'tag'}
  eventBus.emit("ShowQuestionWaitNodeTree",params)
  
}
// 切换是否编辑节点
const swithEditNode =() =>{
  state.isEditNode = !state.isEditNode
}
// 获取自己名下的标签
const getTagAll=()=>{
  console.log('将要获取所有自己名下的标签')
  axios.get('/TagModelViewSet/get_all_tag/').then(res => {
    console.log('获取私有标签：', res)
      if (res.code==200){
          state.tagList = res.data.results
      }else{       
          console.log("error", res.message)
      }
  })
  .catch((error)=>{
      console.log("获取标签错误：", error)
  })
}
// 获取自己名下的章节目录
const getCategoryData=()=>{
  let params = {
    course_id: store.getters.getNodeId
  }
  axios.get('/NodeModelViewSet/get_all_node',{params}).then(res => {
    console.log('获取私有章节知识点：', res)
      if (res.code==200){
          state.chapterSectionMenu = res.data.results
      }else{       
          console.log("error", res.message)
      }
  })
  .catch((error)=>{
      console.log("获取章节菜单错误：", error)
  })
}
// 点击节点事件
const handleNodeClick = (data) => {
  console.log('点击节点了:', data)
  state.selectedNode = {id: data.id, name:data.name}
  let params={selectedNode: state.selectedNode, mode:'chapter'}
  eventBus.emit("ShowQuestionWaitNodeTree",params)
}
onMounted(()=>{
  getCategoryData()
  getTagAll()
})
// 添加子节点,
const append = (data)=>{
  console.log('增加子节点：', data)
  state.addNodeVisible=true
  state.editNodeVisible=false
  state.dialogVisible = true
  state.selectedNode = {id: data.id, name:data.name}
 
}
// 删除子节点
const remove = (data)=> {
  console.log('删除本节点', data)
  let params = {
      node_id: data.id,
  }
  axios.delete(`/NodeModelViewSet/delete_node/`, {params}).then((res) => {
    if(res.code==200){
      ElMessage.success( '删除成功')
      // state.nodeTree = res.data.results
      state.dialogVisible = false;
      getCategoryData()
    }else
    if(res.code==1099){
      ElMessage.warning( '节点不存在！')
    }else
    if(res.code==1095){
      ElMessage.warning( '不是作者')
    }
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}
// 修改节点
const modify = (data)=> {
  console.log('修改本节点', data)
  state.addNodeVisible=false
  state.editNodeVisible=true
  state.dialogVisible = true
  inputCourseName.value = data.name
  state.selectedNode = {id: data.id, name:data.name}
}
// 点击新建节点按钮
const addNode = () => {
  console.log('新建节点啦')
  let params = {
      name: inputCourseName.value,
      parent_id: state.selectedNode.id,
  }
  axios.post(`/NodeModelViewSet/create_node/`, params).then((res) => {
    if(res.code==200){
      ElMessage.success( '创建成功')
      // state.nodeTree = res.data.results
      state.dialogVisible = false;
      getCategoryData()
    }else
    if(res.code==1099){
      ElMessage.warning( '标题不能为空！')
    }else
    if(res.code==1095){
      ElMessage.warning('你不是作者！')
    }
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}
// 修改节点名称
const editNode = () => {
  console.log('修改节点啦')
  if(state.selectedNode.id==0 || inputCourseName==''){
    ElMessage.warning( '请先选择节点，并输入名称')
    return 0
  }
  let params = {
      name: inputCourseName.value,
      node_id: state.selectedNode.id,
  }
  axios.put(`/NodeModelViewSet/modify_name/`, params).then((res) => {
    if(res.code==200){
      ElMessage.success( '修改成功')
      // state.nodeTree = res.data.results
      state.dialogVisible = false;
      getCategoryData()
    }else
    if(res.code==1099){
      ElMessage.warning( '标题不能为空！')
    }else
    if(res.code==1095){
      ElMessage.warning('不是作者')
    }
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}

// 修改节点往上调
const upward = (data) => {
  console.log('往上调整次序啦')
  if(data.previous == 0){
    ElMessage.warning( '该节点是第一个，不能再调整')
    return 0
  }
  let params = {
    node_previous_id: data.previous,
    node_id: data.id,
  }
  axios.put(`/NodeModelViewSet/modify_order/`, params).then((res) => {
    if(res.code==200){
      ElMessage.success('修改次序成功')   
      getCategoryData()
    }else
    if(res.code==1099){
      ElMessage.warning('id不可用！')
    }else
    if(res.code==1095){
      ElMessage.warning('不是作者')
    }  
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}
</script>

<style scoped>
    .tag-mode{     
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
      
      width: 400px;
        /* overflow: hidden; */
      background-color: #fcf2e6;
    }
    .tag-item{
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
    }
    span{
        font-size: 10x;
        color: #000;
    }
    a{
        text-decoration: none;
        color:#333;
        font-family:sans-serif;
        font-size: 10px;
    }
    .custom-tree-node {
      /* flex: 1; */
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      font-size: 10px;
      padding-right: 1px;
    }
    .three-button {
      width: 50px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      margin: 2px;
    }
</style>